package com.books.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.books.enums.BookStatusEnum;
import com.books.mapper.bookInfoMapper;
import com.books.model.BookInfo;
import com.books.model.PageRequest;
import com.books.model.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Slf4j
public class BookService {
    @Autowired
    private bookInfoMapper bookInfoMapper;

    public String addBook(BookInfo bookInfo) {
        if(!StringUtils.hasLength(bookInfo.getBookName())
                ||!StringUtils.hasLength(bookInfo.getPublish())
                ||!StringUtils.hasLength(bookInfo.getAuthor())
                ||(bookInfo.getCount()==null)
                ||bookInfo.getPrice()==null
                ||bookInfo.getStatus()==null){
            log.error("添加图书，参数不合法");
            return "参数不合法";
        }
try{
    bookInfoMapper.addBook(bookInfo);
    log.info("添加图书成功,request:{}",bookInfo);
    return "";
}catch (Exception e){
    log.error("添加图书异常，e:",e);
    return "添加图书发生异常";
}

    }

    public ResponseResult<BookInfo> getListByPage(PageRequest pageRequest){
        int count= bookInfoMapper.count();
        List<BookInfo>bookInfos=bookInfoMapper.selectBookByPage(pageRequest);
        for (BookInfo bookInfo:bookInfos) {
            bookInfo.setStatusCN(BookStatusEnum.getBookInfoStatusCNByStatus(bookInfo.getStatus()).getDesc());

//            if(bookInfo.getStatus()==1){
//                bookInfo.setStatusCN("可借阅");
//            }else {
//                bookInfo.setStatusCN("不可借阅");
//            }
        }
return new ResponseResult<BookInfo>(count,bookInfos,pageRequest);
    }


    public BookInfo queryBookById(Integer bookId) {
        return bookInfoMapper.queryBoookById(bookId);
    }

    public void updateBook(BookInfo bookInfo) {
        bookInfoMapper.updateBook(bookInfo);
    }

    public Boolean batchDelete(List<Integer> ids) {
        try{
            if(ids!=null){
                LambdaUpdateWrapper<BookInfo>wrapper=new LambdaUpdateWrapper<BookInfo>()
                        .in(BookInfo::getId,ids);
                bookInfoMapper.batchDelete(wrapper,BookStatusEnum.DELETE.getCode());
                log.info("批量删除图书成功：ids:{}",ids);
                return true;
            }else {
                log.error("删除的id列表为空，删除图书失败");
                return false;
            }
        }catch (Exception e){
            log.error("批量删除图书失败");
            return false;
        }
    }
}
